package com.grid.camera.pelco;

/** Pelco D协议工具类 提供辅助方法用于调试和显示Pelco D协议数据包 */
public class PelcoDUtils {

    /**
     * 将字节数组转换为十六进制字符串，用于调试显示
     *
     * @param data 字节数组
     * @return 十六进制字符串表示
     */
    public static String bytesToHex(byte[] data) {
        if (data == null) {
            return "null";
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : data) {
            sb.append(String.format("%02X ", b & 0xFF));
        }
        return sb.toString().trim();
    }

    /**
     * 解析Pelco D协议数据包，返回人类可读的描述
     *
     * @param packet Pelco D协议数据包
     * @return 数据包的描述
     */
    public static String parsePacket(byte[] packet) {
        if (packet == null || packet.length != 7) {
            return "无效的数据包";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("Pelco D数据包: ").append(bytesToHex(packet)).append("\n");
        sb.append("同步字节: ").append(String.format("%02X", packet[0] & 0xFF)).append("\n");
        sb.append("地址: ").append(packet[1] & 0xFF).append("\n");

        byte command1 = packet[2];
        byte command2 = packet[3];
        sb.append("命令1: ").append(String.format("%02X", command1 & 0xFF)).append(" (");

        if (command1 == 0) {
            sb.append("无命令");
        } else {
            if ((command1 & PelcoDProtocol.COMMAND_UP) != 0) {
                sb.append("上移 ");
            }
            if ((command1 & PelcoDProtocol.COMMAND_DOWN) != 0) {
                sb.append("下移 ");
            }
        }
        sb.append(")\n");

        sb.append("命令2: ").append(String.format("%02X", command2 & 0xFF)).append(" (");
        if (command2 == 0) {
            sb.append("无命令");
        } else if (command2 == PelcoDProtocol.COMMAND_SET_PRESET) {
            sb.append("设置预设位");
        } else if (command2 == PelcoDProtocol.COMMAND_CLEAR_PRESET) {
            sb.append("清除预设位");
        } else if (command2 == PelcoDProtocol.COMMAND_GOTO_PRESET) {
            sb.append("调用预设位");
        }
        sb.append(")\n");

        sb.append("数据1: ").append(packet[4] & 0xFF).append("\n");
        sb.append("数据2: ").append(packet[5] & 0xFF).append("\n");
        sb.append("校验和: ").append(String.format("%02X", packet[6] & 0xFF));
        sb.append(" (").append(validateChecksum(packet) ? "正确" : "错误").append(")");

        return sb.toString();
    }

    /**
     * 验证Pelco D协议数据包的校验和是否正确
     *
     * @param packet Pelco D协议数据包
     * @return 校验和是否正确
     */
    public static boolean validateChecksum(byte[] packet) {
        if (packet == null || packet.length != 7) {
            return false;
        }

        int sum = 0;
        // 计算字节2-6的加和（索引1-5）
        for (int i = 1; i < 6; i++) {
            sum += packet[i] & 0xFF;
        }
        // 返回16进制值（取低8位）
        byte expectedChecksum = (byte) (sum & 0xFF);

        return expectedChecksum == packet[6];
    }
}
